<?php


namespace app\middleware\api;


use app\api\service\Token;
use app\enum\ScopeEnum;
use app\exception\ForBiddenException;
use app\exception\TokenException;
use think\Exception;

class checkScope
{

    protected $scope = ScopeEnum::User;
    protected $symbol = '>=';
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     *
     * @return Response
     * @throws ForBiddenException
     * @throws TokenException|Exception
     */
    public function handle($request, \Closure $next)
    {
        $scope = Token::getCurrentTokenVar('scope');
        if($scope){
            if($this->interpreter($scope)){
                return $next($request);
            }else{
                throw new ForBiddenException();
            }
        }else{
            throw new TokenException();
        }

    }

    /**
     * @param $scope
     *
     * @return bool
     */
    private  function interpreter($scope): bool
    {
        if($this->symbol == '>=')
            return $this->scope >= $scope;
        else if($this->symbol == "==")
            return $this->scope == $scope;
    }
}